package com.js.rtu.util;

import android.util.Log;

import com.js.rtu.config.CmdConfig;


/**
 * 指令组装工具
 * Created by wz on 2020/6/30.
 */
public class CmdUtils {


    /**
     * 含data的指令
     * 组装命令
     *
     * @param cmd  指令代码
     * @param data 信息段
     * @return 一帧数据
     */
    public static String getCmd(String cmd, String data) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append(CmdConfig.CMD_HEADER).append(" ")
                .append(CmdConfig.CMD_ADDRESS).append(" ");
        //地址固定8字节,crc固定2字节,cmd1字节，Length2字节，共13，
        String length = String.format("%04x", 13 + data.split(" ").length).toUpperCase();//10->16，不满4位补0
        length = length.substring(2, 4) + " " + length.substring(0, 2);//低字节在前
        String crc =  CRC16Util.Make_CRC(CmdConfig.CMD_ADDRESS +" "+ length +" "+ cmd + " " + data);
        stringBuilder
                .append(length).append(" ")
                .append(cmd).append(" ")
                .append(data).append(" ")
                .append(crc).append(" ")
                .append(CmdConfig.CMD_FOOTER);
        Log.e("发送指令",stringBuilder.toString().toUpperCase());
        return stringBuilder.toString().toUpperCase();
    }

    /**
     * 不含data的指令
     * 组装命令
     *
     * @param cmd  指令代码
     * @return 一帧数据
     */
    public static String getCmd(String cmd) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append(CmdConfig.CMD_HEADER).append(" ")
                .append(CmdConfig.CMD_ADDRESS).append(" ");
        //地址固定8字节,crc固定2字节,cmd1字节，Length2字节，共13，
        String length = String.format("%04x", 13 ).toUpperCase();//10->16，不满4位补0
        length = length.substring(2, 4) + " " + length.substring(0, 2);//低字节在前
        String crc=CmdConfig.CMD_ADDRESS +" "+ length +" "+ cmd;
         crc =  CRC16Util.Make_CRC(crc );
        stringBuilder
                .append(length).append(" ")
                .append(cmd).append(" ")
                .append(crc).append(" ")
                .append(CmdConfig.CMD_FOOTER);
        Log.e("发送指令",stringBuilder.toString().toUpperCase());
        return stringBuilder.toString().toUpperCase();
    }



}
